package com.atguigu.spzx.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.dto.user.UserLoginDto;
import com.atguigu.spzx.model.dto.user.UserRegisterDto;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.spzx.user.mapper.UserInfoMapper;
import com.atguigu.spzx.user.service.UserInfoService;
import com.atguigu.spzx.user.utils.HttpUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void register(UserRegisterDto userRegisterDto) {
        // 1获取数据
        String username = userRegisterDto.getUsername();  //因为只能用手机注册,所以这里的username就是手机号
        String password = userRegisterDto.getPassword();
        String nickName = userRegisterDto.getNickName();
        String code = userRegisterDto.getCode();
        //进行数据不为空校验
        Assert.isTrue(!(StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(password) ||
                StringUtils.isEmpty(nickName) ||
                StringUtils.isEmpty(code)),"有参数为空");
        //2去redis中进行验证码校验
        String redisCodeValue = redisTemplate.opsForValue().get("phone:code:" + username);
        Assert.isTrue(code.equals(redisCodeValue),"验证码错误");
        //获取到了验证码后,清空缓存里的验证码
        redisTemplate.delete("phone:code:" + username);
        //3进行用户名检查是否唯一
        Integer count= userInfoMapper.selectCountByUsername(username);
        Assert.isTrue(count<=0,"用户名已存在");
        //4封装数据,存入数据库
        UserInfo userInfo=new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userInfo.setAvatar("https://tiebapic.baidu.com/forum/w%3D580/sign=9f6376d4b103918fd7d13dc2613d264b/fb2ba6c27d1ed21bf2b00fd1eb6eddc450da3fcc.jpg?tbpicau=2025-01-01-05_2a57bd329e2ea4cb0bf5f65569b86877");
        userInfo.setNickName(nickName);
        userInfo.setPhone(username);
        userInfoMapper.insertUserInfo(userInfo);


    }

    @Override
    public void sendValidateCode(String phone) {
        //生成随机验证码
        String code = RandomStringUtils.randomNumeric(4);
        //发送验证码
        sendSmsCode(phone,code);
        //把验证码存入redis缓存一份
        redisTemplate.opsForValue().set("phone:code:" + phone,code,5, TimeUnit.MINUTES);
    }

    @Override
    public String login(UserLoginDto userLoginDto, String ip) {
        String username = userLoginDto.getUsername();
        String password = userLoginDto.getPassword();
        //判断参数不为空
        Assert.isTrue(username!=null && password!=null,"用户名或密码不能为空");
        //根据用户id查询用户
        UserInfo userInfo= userInfoMapper.selectByUsername(username);
        //进行登录数据校验
        Assert.notNull(userInfo,"用户名不存在");
        String passwordMd5 = DigestUtils.md5DigestAsHex(password.getBytes());
        Assert.isTrue(passwordMd5.equals(userInfo.getPassword()),"密码错误");
        //进行用户登录信息更新
        userInfo.setLastLoginIp(ip);
        userInfo.setLastLoginTime(new Date());
        userInfoMapper.updateById(userInfo);
        //生成token,并把用户数据存入redis缓存
        String token= UUID.randomUUID().toString().replace("-","");
        redisTemplate.opsForValue().set("user:login:"+token, JSON.toJSONString(userInfo),30,TimeUnit.DAYS);
        return token;
    }

    @Override
    public UserInfo checkUserInfo(String token) {
        //通过token去redis缓存里获取当前用户信息
        String userInfoJson = redisTemplate.opsForValue().get("user:login:" + token);
        Assert.notNull(userInfoJson,"用户不存在");
        return JSON.parseObject(userInfoJson, UserInfo.class);
    }

    private void sendSmsCode(String phone, String code) {
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "4fb0529bcf2a417685b9286f4b51a05d";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        querys.put("param", "**code**:"+code+",**minute**:5");

//smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。参考文档：http://help.guoyangyun.com/Problem/Qm.html

        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        Map<String, String> bodys = new HashMap<String, String>();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从\r\n\t    \t* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java\r\n\t    \t* 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //System.out.println(response.toString());
            //获取response的body
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
